use ggez::{Context, GameResult};
use ggez::event::EventHandler;
use ggez::graphics::{self, Color, DrawParam};
use nalgebra::Point2;
use crate::tank::Tank;
use crate::combat::Bullet;
use crate::ai::{TankAI, AdvancedAI, TankPerception, TankState, EnemyState, Obstacle, Powerup, PowerupType, Bullet as AIBullet};
use crate::map::GameMap;
use crate::game_prop::GameProp;

pub struct Game {
    tanks: Vec<Tank>,
    bullets: Vec<Bullet>,
    map: GameMap,
    props: Vec<GameProp>,
    ais: Vec<Box<dyn TankAI>>,
    game_time: f32,
}

impl Game {
    pub fn new(_ctx: &Context) -> GameResult<Self> {
        let mut map = GameMap::new(20, 15);
        
        // 设置一些地图元素
        for x in 5..10 {
            map.set_tile(x, 5, crate::map::MapTile::Brick);
        }
        
        for x in 12..17 {
            map.set_tile(x, 10, crate::map::MapTile::Wall);
        }
        
        // 设置出生点
        map.set_tile(2, 2, crate::map::MapTile::SpawnPoint);
        map.set_tile(17, 2, crate::map::MapTile::SpawnPoint);
        map.set_tile(2, 12, crate::map::MapTile::SpawnPoint);
        map.set_tile(17, 12, crate::map::MapTile::SpawnPoint);
        
        // 设置资源点
        map.set_tile(10, 7, crate::map::MapTile::ResourcePoint);
        map.set_tile(5, 12, crate::map::MapTile::ResourcePoint);
        map.set_tile(15, 2, crate::map::MapTile::ResourcePoint);
        
        let mut tanks = Vec::new();
        let mut ais = Vec::new();
        
        // 创建坦克和AI
        for (i, spawn_point) in map.get_spawn_points().iter().enumerate() {
            let team = i % 2; // 两个队伍
            let tank = Tank::new(*spawn_point, i, team);
            tanks.push(tank);
            
            let ai = AdvancedAI::new(10.0); // 10次/秒的决策频率
            ais.push(Box::new(ai) as Box<dyn TankAI>);
        }
        
        // 创建道具
        let mut props = Vec::new();
        for resource_point in map.get_resource_points() {
            use rand::Rng;
            let mut rng = rand::thread_rng();
            let prop_type = match rng.gen_range(0..5) {
                0 => crate::game_prop::GamePropType::Health,
                1 => crate::game_prop::GamePropType::Invincible,
                2 => crate::game_prop::GamePropType::Range,
                3 => crate::game_prop::GamePropType::Speed,
                _ => crate::game_prop::GamePropType::Damage,
            };
            props.push(GameProp::new(*resource_point, prop_type));
        }
        
        Ok(Game {
            tanks,
            bullets: Vec::new(),
            map,
            props,
            ais,
            game_time: 0.0,
        })
    }
    
    // 获取视野内的敌人信息
    fn get_enemies_in_vision(tanks: Vec<Tank>, tank_id: usize, vision_range: f32) -> Vec<EnemyState> {
        let mut enemies = Vec::new();
        let tank = tanks[tank_id];
        
        for (i, enemy) in tanks.iter().enumerate() {
            if i != tank_id && enemy.team != tank.team && enemy.is_alive() {
                let distance = (tank.position - enemy.position).magnitude();
                if distance <= vision_range {
                    enemies.push(EnemyState {
                        position: enemy.position,
                        health: enemy.health,
                        threat_level: 100.0 - distance, // 距离越近威胁越大
                        speed: enemy.speed,
                        attack_range: enemy.attack_range,
                    });
                }
            }
        }
        
        enemies
    }
    
    // 获取视野内的道具信息

}

impl EventHandler for Game {
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        let dt = ggez::timer::delta(ctx).as_secs_f32();
        self.game_time += dt;
        
        // 更新AI
        for (i, ai) in self.ais.iter_mut().enumerate() {
            ai.update(dt);
        }
        
        // AI决策和执行
        for (i, ai) in self.ais.iter_mut().enumerate() {
            if let Some(tank) = self.tanks.get(i) {
                if !tank.is_alive() {
                    continue;
                }
                
                // 构建感知信息
                let perception = TankPerception {
                    self_state: TankState {
                        position: tank.position,
                        health: tank.health,
                        attack_damage: tank.attack_damage,
                        speed: tank.speed,
                        attack_range: tank.attack_range,
                    },
                    allies: Vec::new(), // 简化处理
                    enemies: get_enemies_in_vision(&self.tanks,i, 200.0),
                    obstacles: Vec::new(), // 简化处理
                    powerups: get_props_in_vision(&self.tanks,& self.props,i, 150.0),
                    bullets: Vec::new(), // 简化处理
                };
                
                // 获取AI决策
                let action = ai.decide(&perception);
                
                // 执行决策
                match action {
                    crate::ai::TankAction::Move(direction, speed) => {
                        let norm = (direction.0 * direction.0 + direction.1 * direction.1).sqrt();
                        if norm > 0.0 {
                            let dx = direction.0 / norm * speed * dt;
                            let dy = direction.1 / norm * speed * dt;
                            self.tanks[i].position.x += dx;
                            self.tanks[i].position.y += dy;
                        }
                    },
                    crate::ai::TankAction::Attack(target) => {
                        if self.tanks[i].attack() {
                            let direction = target - self.tanks[i].position;
                            let norm = direction.magnitude();
                            if norm > 0.0 {
                                let normalized_direction = direction / norm;
                                self.bullets.push(Bullet::new(
                                    self.tanks[i].position,
                                    normalized_direction.into(),
                                    i,
                                ));
                            }
                        }
                    },
                    crate::ai::TankAction::Stay => {
                        // 保持不动
                    },
                    crate::ai::TankAction::Retreat(direction) => {
                        let norm = (direction.x * direction.x + direction.y * direction.y).sqrt();
                        if norm > 0.0 {
                            let dx = direction.x / norm * tank.speed * dt;
                            let dy = direction.y / norm * tank.speed * dt;
                            self.tanks[i].position.x += dx;
                            self.tanks[i].position.y += dy;
                        }
                    },
                }
            }
        }
        
        // 更新坦克状态
        for tank in self.tanks.iter_mut() {
            tank.update(dt);
        }
        
        // 更新炮弹
        self.bullets.retain_mut(|bullet| {
            let active = bullet.update(dt);
            if !active {
                return false;
            }
            
            // 检查碰撞
            for (i, tank) in self.tanks.iter_mut().enumerate() {
                if i != bullet.owner && tank.is_alive() {
                    if crate::combat::CollisionSystem::check_bullet_tank_collision(bullet, tank) {
                        tank.take_damage(bullet.damage);
                        return false; // 炮弹销毁
                    }
                }
            }
            
            // 检查是否击中障碍物（简化处理）
            let x = bullet.position.x as usize;
            let y = bullet.position.y as usize;
            if !self.map.is_passable(x, y) {
                return false; // 炮弹销毁
            }
            
            true
        });
        
        // 更新道具
        for prop in self.props.iter_mut() {
            prop.update(dt);
        }
        
        // 检查坦克与道具的碰撞
        for (i, tank) in self.tanks.iter_mut().enumerate() {
            if !tank.is_alive() {
                continue;
            }
            
            for prop in self.props.iter_mut() {
                if prop.active && !prop.collected {
                    if crate::combat::CollisionSystem::check_tank_prop_collision(tank, prop.position) {
                        if prop.collect() {
                            tank.apply_prop(prop.game_prop_type, prop.value, prop.duration);
                        }
                    }
                }
            }
        }
        
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        // 清屏
        let mut canvas = graphics::Canvas::from_frame(ctx, graphics::Color::from([0.1, 0.2, 0.3, 1.0]));
        
        // 绘制地图
        for x in 0..self.map.width {
            for y in 0..self.map.height {
                let tile_color = match self.map.get_tile(x, y) {
                    Some(crate::map::MapTile::Empty) => graphics::Color::from([0.0, 0.0, 0.0, 1.0]),
                    Some(crate::map::MapTile::Wall) => graphics::Color::from([0.5, 0.5, 0.5, 1.0]),
                    Some(crate::map::MapTile::Brick) => graphics::Color::from([0.8, 0.4, 0.2, 1.0]),
                    Some(crate::map::MapTile::SpawnPoint) => graphics::Color::from([0.0, 1.0, 0.0, 1.0]),
                    Some(crate::map::MapTile::ResourcePoint) => graphics::Color::from([1.0, 1.0, 0.0, 1.0]),
                    None => graphics::Color::from([0.0, 0.0, 0.0, 1.0]),
                };
                
                let rect = graphics::Rect::new(x as f32 * 32.0, y as f32 * 32.0, 32.0, 32.0);
                canvas.draw(&graphics::Quad, DrawParam::default().dest(rect.point()).scale(rect.size()).color(tile_color));
            }
        }
        
        // 绘制坦克
        for tank in &self.tanks {
            if tank.is_alive() {
                let tank_color = if tank.team == 0 {
                    graphics::Color::from([1.0, 0.0, 0.0, 1.0]) // 红色队伍
                } else {
                    graphics::Color::from([0.0, 0.0, 1.0, 1.0]) // 蓝色队伍
                };
                
                let rect = graphics::Rect::new(tank.position.x - 10.0, tank.position.y - 10.0, 20.0, 20.0);
                canvas.draw(&graphics::Quad, DrawParam::default().dest(rect.point()).scale(rect.size()).color(tank_color));
            }
        }
        
        // 绘制炮弹
        for bullet in &self.bullets {
            let rect = graphics::Rect::new(bullet.position.x - 3.0, bullet.position.y - 3.0, 6.0, 6.0);
            canvas.draw(&graphics::Quad, DrawParam::default().dest(rect.point()).scale(rect.size()).color(graphics::Color::from([1.0, 1.0, 1.0, 1.0])));
        }
        
        // 绘制道具
        for prop in &self.props {
            if prop.active {
                let prop_color = match prop.game_prop_type {
                    crate::game_prop::GamePropType::Health => graphics::Color::from([1.0, 0.0, 0.0, 1.0]),
                    crate::game_prop::GamePropType::Invincible => graphics::Color::from([0.5, 0.5, 1.0, 1.0]),
                    crate::game_prop::GamePropType::Range => graphics::Color::from([0.0, 1.0, 0.0, 1.0]),
                    crate::game_prop::GamePropType::Speed => graphics::Color::from([1.0, 1.0, 0.0, 1.0]),
                    crate::game_prop::GamePropType::Damage => graphics::Color::from([1.0, 0.0, 1.0, 1.0]),
                };
                
                let rect = graphics::Rect::new(prop.position.x - 8.0, prop.position.y - 8.0, 16.0, 16.0);
                canvas.draw(&graphics::Quad, DrawParam::default().dest(rect.point()).scale(rect.size()).color(prop_color));
            }
        }
        
        // 提交绘制
        canvas.finish(ctx)
    }
}


fn get_enemies_in_vision(tanks: &[Tank], tank_id: usize, vision_range: f32) -> Vec<EnemyState> {
    let mut enemies = Vec::new();
    let tank = tanks[tank_id];

    for (i, enemy) in tanks.iter().enumerate() {
        if i != tank_id && enemy.team != tank.team && enemy.is_alive() {
            let distance = (tank.position - enemy.position).magnitude();
            if distance <= vision_range {
                enemies.push(EnemyState {
                    position: enemy.position,
                    health: enemy.health,
                    threat_level: 100.0 - distance, // 距离越近威胁越大
                    speed: enemy.speed,
                    attack_range: enemy.attack_range,
                });
            }
        }
    }

    enemies
}
fn get_props_in_vision(tanks: &[Tank], props: &[GameProp], tank_id: usize, vision_range: f32) -> Vec<Powerup> {
    let mut powerups = Vec::new();
    let tank = tanks[tank_id];

    for prop in props {
        if prop.active {
            let distance = (tank.position - prop.position).magnitude();
            if distance <= vision_range {
                powerups.push(Powerup {
                    position: prop.position,
                    powerup_type: match prop.game_prop_type {
                        crate::game_prop::GamePropType::Health => PowerupType::Health,
                        crate::game_prop::GamePropType::Invincible => PowerupType::Health, // 简化处理
                        crate::game_prop::GamePropType::Range => PowerupType::Range,
                        crate::game_prop::GamePropType::Speed => PowerupType::Speed,
                        crate::game_prop::GamePropType::Damage => PowerupType::Damage,
                    },
                    remaining_time: prop.respawn_time - prop.current_respawn,
                });
            }
        }
    }

    powerups
}